package org.tom.petcart.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.tom.petcart.dto.SaveCartOrderDto;
import org.tom.petcart.service.IPetCartService;
import org.tom.basic.exception.MyException;
import org.tom.basic.util.JsonResult;

import java.util.List;

@RestController
@RequestMapping("/addCart")
public class PetCartController {
    @Autowired
    private IPetCartService petCartService;

    @GetMapping("/{petid}")
    public JsonResult addCart(@PathVariable Long petid){
        try {
            return petCartService.addCart(petid);
        }catch (MyException e){
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("后端系统异常");
        }

    }

    @PostMapping("/list")
    public JsonResult getShopCartList(){
        try {
            return petCartService.getShopCartList();
        }catch (MyException e){
            e.printStackTrace();
           return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("后端系统异常");
        }
    }

    @DeleteMapping("{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            petCartService.delete(id);
            return JsonResult.me();
        }catch (MyException e){
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("后端系统异常");
        }
    }

    /**
     * 计算金额
     * @param ids
     * @return
     */
    @PostMapping("/cal")
    public JsonResult cal(@RequestBody List<Long> ids){
        try {
            return petCartService.cal(ids);
        }catch (MyException e){
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("后端系统异常");
        }
    }

    @PostMapping("/ordersave")
    public JsonResult commitPetOrder (@RequestBody SaveCartOrderDto saveCartOrderDtoOrderDto){
        try {
            String sn = petCartService.commitPetOrder(saveCartOrderDtoOrderDto);
            return JsonResult.me().setResultObj(sn);
        }catch (MyException e){
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("后端系统异常");
        }
    }

}
